package com.wb3.meta.api.core.controller;

import com.wb3.meta.api.core.service.MyToysService;
import com.wb3.meta.common.annotation.RequireAuth;
import com.wb3.meta.common.pojo.ResultT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutImageMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Slf4j
@AllArgsConstructor
@RestController
@Api(tags = "微信公众号接口")
@RequestMapping("/wx/portal/{appid}")
public class WxPortalController {
    private final WxMpService wxService;
    private final WxMpMessageRouter messageRouter;

    private final MyToysService myToysService;

    @ApiOperation("微信公众号认证接口")
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appid,
                          @RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            if ("event".equals(inMessage.getMsgType())) {
                if ("subscribe".equals(inMessage.getEvent())) {
                    out = outMessage.toXml();
                }else{
                    if ("V1001_PUSH_QRCODE".equals(inMessage.getEventKey())) {
                        WxMpXmlOutImageMessage imageMessage = WxMpXmlOutMessage.IMAGE().
                                mediaId("GuYsbRoBjtEQvw2FLXLYYbmw5963MXQBeyxFjj65yOdbrit9KjGMLLLjgydjCDH_").
                                fromUser(inMessage.getToUser()).toUser(inMessage.getFromUser()).build();
                        out = imageMessage.toXml();
                    }
                }
            } else if ("text".equals(inMessage.getMsgType())) {
                String msg = myToysService.getWawaByMp(inMessage.getFromUser(), inMessage.getContent());
                WxMpXmlOutTextMessage textMessage = WxMpXmlOutMessage.TEXT().content(msg).
                        fromUser(inMessage.getToUser()).toUser(inMessage.getFromUser()).build();
                out = textMessage.toXml();
            }else{
                out = outMessage.toXml();
            }

//            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());

        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }

    @ApiOperation("图片上传到微信公众号")
    @PostMapping("upload")
    public String uploadImgToWx(@RequestBody MultipartFile file) throws IOException, WxErrorException {
        WxMediaUploadResult res = wxService.getMaterialService().mediaUpload("image", "png", file.getInputStream());
// 或者
//        res = wxService.getMaterialService().mediaUpload("image", file);
//        res.getType();
//        res.getCreatedAt();
//
//        res.getThumbMediaId();
        return res.getMediaId();
    }

}
